package com.ruoyi.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.domain.CarEntryLog;
import com.ruoyi.system.domain.CarLeaveLog;
import com.ruoyi.system.domain.ReportInfo;
import com.ruoyi.system.service.ICarEntryLogService;
import com.ruoyi.system.service.ICarLeaveLogService;
import com.ruoyi.system.service.IReportInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysConfigService configService;

    @Value("${appId}")
    private String appId;

    @Value("${parkId}")
    private String parkId;

    @Autowired
    private IReportInfoService reportInfoService;

    @Autowired
    private ICarEntryLogService iCarEntryLogService;

    @Autowired
    private ICarLeaveLogService iCarLeaveLogService;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @GetMapping("/getYiQing")
    public AjaxResult getYiQing(ReportInfo reportInfo) {
        String url = "https://ditu.so.com/app/yiqing/policy?from=" + reportInfo.getOriginPlace();
        String s = HttpRequest.get(url)
                .header("origin", "http://ditu.so.com")
                .header("accept", "*/*")
                .header("accept-encoding", "gzip, deflate, br")
                .header("accept-language", "zh-CN")
                .header("connection", "keep-alive")
                .execute().body();
        return success(s);
    }

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = success();
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        ajax.put("captchaOnOff", captchaOnOff);
        if (!captchaOnOff)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }


    @RequestMapping(value = "/PostCarInInfo")
    public AjaxResult postCarInInfo(@RequestBody JSONObject jsonObject) throws ParseException {
        System.out.println(jsonObject);
        if(!jsonObject.isEmpty()){
            if(jsonObject.get("appId").equals(appId) && jsonObject.get("parkId").equals(parkId)){

                CarEntryLog carEntryLog = new CarEntryLog();
                carEntryLog.setId(IdUtil.simpleUUID());
                carEntryLog.setPlateNo(String.valueOf(jsonObject.get("plateNo")));
                carEntryLog.setEntryTime(String.valueOf(jsonObject.get("entryTime")));
                carEntryLog.setImgname(String.valueOf(jsonObject.get("imgInfo")));
                carEntryLog.setEntryPlace(String.valueOf(jsonObject.get("entryPlace")));
                ReportInfo reportInfo1 = new ReportInfo();
                reportInfo1.setCarNumber(String.valueOf(jsonObject.get("plateNo")));
                reportInfo1.setComeTime((sdf.parse(String.valueOf(jsonObject.get("entryTime")))));
                List<ReportInfo> reportInfos = reportInfoService.selectReportInfoByCarNumber(reportInfo1);
                if(reportInfos.size()>0){
                    carEntryLog.setReportId(reportInfos.get(0).getId());
                }
                iCarEntryLogService.insertCarEntryLog(carEntryLog);
                return success("上报成功");

            }else{
                return success("appId与parkId不匹配");
            }

        }else{
            return error("请求参数不能为空");
        }
    }

    @RequestMapping(value = "/PostCarOutInfo")
    public AjaxResult postCarOutInfo(@RequestBody JSONObject jsonObject) throws ParseException {
        System.out.println(jsonObject);
        if(!jsonObject.isEmpty()){
            if(jsonObject.get("appId").equals(appId) && jsonObject.get("parkId").equals(parkId)){

                CarLeaveLog carLeaveLog = new CarLeaveLog();
                carLeaveLog.setId(IdUtil.simpleUUID());
                carLeaveLog.setPlateNo(String.valueOf(jsonObject.get("plateNo")));
                carLeaveLog.setLeaveTime(String.valueOf(jsonObject.get("entryTime")));
                carLeaveLog.setImgname(String.valueOf(jsonObject.get("imgInfo")));
                carLeaveLog.setLeavePlace(String.valueOf(jsonObject.get("leavePlace")));
                ReportInfo reportInfo1 = new ReportInfo();
                reportInfo1.setCarNumber(String.valueOf(jsonObject.get("plateNo")));
                reportInfo1.setComeTime((sdf.parse(String.valueOf(jsonObject.get("entryTime")))));
                List<ReportInfo> reportInfos = reportInfoService.selectReportInfoByCarNumber(reportInfo1);
                if(reportInfos.size()>0){
                    carLeaveLog.setReportId(reportInfos.get(0).getId());
                }
                iCarLeaveLogService.insertCarLeaveLog(carLeaveLog);
                return success("上报成功");

            }else{
                return success("appId与parkId不匹配");
            }

        }else{
            return error("请求参数不能为空");
        }
    }
}
